
import { _decorator, Component, Node } from 'cc';
const { ccclass, property } = _decorator;

import Colyseus from 'db://colyseus-sdk/colyseus.js';

@ccclass('NetworkManager')
export class NetworkManager extends Component {
    @property address = "localhost:2567";
    @property useSSL = false;

    client !: Colyseus.Client;

    lobby !: Colyseus.Room;
    room !: Colyseus.Room;

    // 
    availableRooms: Colyseus.RoomAvailable[] = [];

    start() {

        // 实例化 Colyseus 客户端
        // 连接到 (ws|wss)://hostname[:port]
        // this.client = new Colyseus.Client(`${this.useSSL ? "wss" : "ws"}://${this.hostname}${([443, 80].includes(this.port) || this.useSSL) ? "" : `:${this.port}`}`);
        this.client = new Colyseus.Client(`${this.useSSL ? "wss" : "ws"}:${this.address}`);

        // 连接到 room
        this.connect();

        this.lobby.onMessage("rooms", (rooms) => {
            this.availableRooms = rooms;
            // TODO 通知刷新UI
        });

        this.lobby.onMessage("+", ([roomId, room]) => {
            const roomIndex = this.availableRooms.findIndex((room) => room.roomId === roomId);
            if (roomIndex !== -1) {
                this.availableRooms[roomIndex] = room;

            } else {
                this.availableRooms.push(room);
            }
            // TODO 通知刷新UI
        });

        this.lobby.onMessage("-", (roomId) => {
            this.availableRooms = this.availableRooms.filter((room) => room.roomId !== roomId);
            // TODO 通知刷新UI
        });


    }

    // update (deltaTime: number) {
    //     // [4]
    // }

    // 连接服务器
    async connect() {
        try {

        } catch (e) {
            console.error(e);
        }
    }

    createRoom() {

    }

    joinRoom() {

    }

    leaveRoom() {

    }

}

